﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.DeepProcess;
using Provenance.Infra.Repositories.DeepProcess;
using Provenance.Write.Api.Application.Command.DeepProcess;

namespace Provenance.Write.Api.Application.CommandHandler.DeepProcess
{
    public class UpAuxiliaryMaterialCommandHandler : IRequestHandler<UpAuxiliaryMaterialCommand, ApiResult>
    {
        private readonly IAuxiliaryMaterialRepository _auxiliaryMaterialRepository;
        private readonly ILogger<UpAuxiliaryMaterialCommandHandler> _logger;
        private readonly IMapper _mapper;
        public UpAuxiliaryMaterialCommandHandler(IAuxiliaryMaterialRepository auxiliaryMaterialRepository, ILogger<UpAuxiliaryMaterialCommandHandler> logger, IMapper mapper)
        {
            _auxiliaryMaterialRepository = auxiliaryMaterialRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpAuxiliaryMaterialCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _auxiliaryMaterialRepository.GetAsync(x => x.AuxiliaryMaterialId == request.AuxiliaryMaterialId);
                obj = _mapper.Map(request, obj);
                await _auxiliaryMaterialRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error updating auxiliary material: " + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
